const express = require("express");
const OrdersDB = require("../model/sqlite/orders");
const config = require("../common/config");
const util = require("../common/util");
const CartDB = require("../model/sqlite/cart");
const GoodsDB = require("../model/sqlite/goods");
const { AlipaySdk } = require("alipay-sdk");
const { sign } = require("alipay-sdk");

const alipaySdk = new AlipaySdk({
    signType: "RSA2", // 必须明确指定
    charset: "utf-8", // 明确字符集
  appId: "9021000141699932",
  encryptKey: "", //这里是开放平台的AES密钥

  privateKey:
    "MIIEowIBAAKCAQEAicb00mgdsd1pSRQ9drYIuwOChFfY0if4oFMIHLrqqhWzmDFZWS8+vRFGZN6AO4mp1LS/caLdudRJh1FGrYHDJ2LNdpLPFMXgk+c9RxY0PQFJwG2asloZnrqb2b+CaJGRd3mAmZr6sEOlfP4utk7rnuoqpwKkWCnFnd/YCNLH5SK20WBBm3EmqBT4ZQfPxsfakS/kI6wXJ0RuGSRvTp+zZUrWpQSXtF7y8wzPsmR337oOAYyyW+mW9JaOyPeRyLb6qJmjzBjojo4jJmK+eFM3IWA7ia+li5afNwzkBdT7QWcLRSXuJUoutA6fOUDHAXe1a6KedzJWIUETfM4nn8xOyQIDAQABAoIBAGZkyJp+6mK/zHmVY0CQdNiX+S3mI6u8LRjp3IONns0dJ8YaFu8jH5tf9VMN0XtuChuc4RLRGbv7u1Gn48EbSTBCS7St0tz7WrZRCseEBvq3tFogmvGl6JiA00b2/zI7zUJfuGVwOpM5Ewpb1deDu7T1DxHj8sPa95UnQOT90bXGB4q0NxEyzNFvYINjHvcjBMvjAvxCu4lX48I1omHbx7GxOh6o6Xjv00uB03b8M2VQ3gImppsHJYAWZte2YeTRJw4dCIBljheoeJR/6FgZByxSfisghrQqD4CldY+BtK0MnCBGu/gtTTskLixI11tr4pDqFDyFpW3zRMU0Ndx9eAECgYEA1LYbEz2o4WbXoAwmx6ivtppmSdaUAJ3UQj0XBFnIMoPrKtg7Nl5j1skRKQObQAgLnNqBV0xuzKDv9ZtrDEs0+wnoZ2DvGz0lvBP/qSWYqFL00vPFy52/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ooT+rfkE4dvqdFo8dUL1fMFs40wNnLMXvOZ5DVDiKE9iOKqz9GoOtY1IWhJkr+0Qp0tlwoTUuySwcE3VHoOmJmAE/pveywfQIDAQAB", // 使用 PEM 格式
  gateway: "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
});
// 引入支付宝 SDK
function gopay(req, res) {
  (async () => {
    try {
      const { orderIds, amount } = req.body;

      if (typeof amount !== "number" || amount <= 0) {
        return util.FormatJSONData(res, 400, "请输入有效的金额");
      }
      if (!Array.isArray(orderIds) || orderIds.length === 0) {
        return util.FormatJSONData(res, 400, "必须提供订单号列表");
      }
      // 🔥 将 orderIds 设置为全局变量
      global.currentOrderIds = orderIds;
      // 生成唯一订单号
      const orderNumber = generateOrderNumber();

      // 使用 pageExec 方法生成支付链接
      const result = await alipaySdk.pageExec("alipay.trade.page.pay", {
        method: "GET",
        bizContent: {
          out_trade_no: orderNumber,
          product_code: "FAST_INSTANT_TRADE_PAY",
          total_amount: amount.toFixed(2),
          subject: "校园二手订单",
          body: "批量支付",
        },
        notifyUrl: "http://127.0.0.1:3006/orders/notify",
        returnUrl: "http://localhost:5006/order",
      });
      // 返回支付链接
      res.json(
        util.FormatJSONData(200, "支付链接生成成功", {
          paymentUrl: result,
          orderNumber,
        })
      );
    } catch (err) {
      console.error("生成支付链接失败:", err);
      res.status(500).json(util.FormatJSONData(500, "服务器内部错误"));
    }
  })();
}
function generateOrderNumber() {
  const now = new Date();
  const datePart = [
    now.getFullYear(),
    String(now.getMonth() + 1).padStart(2, "0"),
    String(now.getDate()).padStart(2, "0"),
    String(now.getHours()).padStart(2, "0"),
    String(now.getMinutes()).padStart(2, "0"),
    String(now.getSeconds()).padStart(2, "0"),
  ].join("");

  const randomPart = Math.floor(100000 + Math.random() * 900000);
  return `${datePart}${randomPart}`;
}

function handleAlipayNotify(req, res) {
  (async () => {
    try {
      console.log("#########################");
      const notifyData = req.body;

      // 验证签名
       const signVerified = alipaySdk.checkNotifySign(notifyData);
      if (!signVerified) {
        console.log("签名验证失败");
        return res.status(400).json(util.FormatJSONData(400, "签名验证失败"));
      }

      // 处理支付结果
      if (notifyData.trade_status === "TRADE_SUCCESS") {
        const outTradeNo = notifyData.out_trade_no;
        const ordersDb = OrdersDB.getInstance();
        await ordersDb.connect();

        // 📌 从全局变量中获取 orderIds
        const orderIds = global.currentOrderIds;

        if (orderIds && Array.isArray(orderIds)) {
          for (let orderId of orderIds) {
            console.log("id为：", orderId);
            await ordersDb.update(orderId, 1); // 更新状态为已付款
            console.log(`订单 ${orderId} 支付成功`);
          }
        } else {
          console.warn("没有找到待更新的订单ID");
        }
      }
      res.send("success");
    } catch (err) {
      console.error("处理支付宝回调失败:", err);
      res.status(500).send("fail");
    }
  })();
}
/**
 * 立即购买接口
 * @param {express.Request} req 请求对象
 * @param {express.Response} res 响应对象
 */
async function buyNow(req, res) {
    (async () => {
        try {
            // 1. 参数校验
            const { buyer_id, item_id } = req.body;
            if (!buyer_id || !item_id) {
                return res.status(400).json(util.FormatJSONData(400, "缺少必要参数: buyer_id 或 item_id"));
            }

            // 2. 初始化数据库连接
            const goodsDb = GoodsDB.getInstance();
            await goodsDb.connect();

            // 3. 查询商品信息
            const goodsInfo = await goodsDb.findById(item_id);
            if (!goodsInfo) {
                return res.status(404).json(util.FormatJSONData(404, "商品不存在"));
            }

            if (goodsInfo.goods_stock < 1) {
                return res.status(400).json(util.FormatJSONData(400, "商品库存不足"));
            }

            const seller_id = goodsInfo.seller;

            // 4. 构建订单数据（quantity 固定为 1）
            const orders_number = generateOrderNumber(); // 复用已有生成订单号的方法
            const orderData = {
                orders_number,
                buyer_id,
                seller_id,
                item_id,
                quantity: 1, // 立即购买数量固定为1
                total_price: goodsInfo.goods_price, // 单价 × 数量 = 总价
                created_at: new Date().toISOString(),
                order_status: 0 // 默认状态：待支付
            };

            // 5. 插入订单
            const ordersDb = OrdersDB.getInstance();
            await ordersDb.connect();
            const result = await ordersDb.add(orderData);

              // ✅ 6. 更新商品库存（减1）
            goodsInfo.goods_stock -= 1; // 库存减一
            await goodsDb.update(goodsInfo); // 调用 goods.update 方法更新商品信息

            // 7. 返回成功响应
            res.json(util.FormatJSONData(201, "订单创建成功，库存已减少", { orders: result }));
        } catch (err) {
            util.err("立即购买失败", err);
            res.status(500).json(util.FormatJSONData(500, "服务器内部错误"));
        }
    })();
}
// 添加订单信息
function addorders(req, res) {
  (async () => {
    let db_cart, goodsDb;
    try {
      // 参数校验
      const requiredFields = ["buyer_id", "item_id"];
      const missing = requiredFields.filter((field) => !(field in req.body));
      if (missing.length > 0) {
        return util.FormatJSONData(res, 400, "缺少必要参数", { missing });
      }

      const buyer_id = req.body.buyer_id;
      const item_id = req.body.item_id;

      // 初始化数据库连接
      goodsDb = GoodsDB.getInstance();
      await goodsDb.connect();

      // 查询商品信息（含 seller_id）
      const goodsInfo = await goodsDb.findById(item_id);
      if (!goodsInfo) {
        return util.FormatJSONData(res, 404, "商品不存在");
      }

      const seller_id = goodsInfo.seller;

      // 初始化购物车数据库连接
      db_cart = CartDB.getInstance();
      await db_cart.connect();

      // 查询购物车数据
      const result_cart = await db_cart.findByPrimaryKey(buyer_id, item_id);
      if (
        !result_cart ||
        !("quantity" in result_cart) ||
        !("money" in result_cart)
      ) {
        return util.FormatJSONData(res, 400, "购物车中无有效商品信息");
      }

      // 生成订单号
      const orders_number = generateOrderNumber();

      // 构建订单对象
      const orders = {
        orders_number,
        buyer_id,
        seller_id,
        item_id,
        quantity: result_cart.quantity,
        total_price: result_cart.money,
        created_at: new Date().toISOString(),
        order_status: 0,
      };

      // 初始化订单数据库连接
      const ordersDb = OrdersDB.getInstance();
      await ordersDb.connect();

      // 插入订单
      const result = await ordersDb.add(orders);

      // 返回成功响应
      res
        .status(200)
        .json(util.FormatJSONData(201, "订单添加成功", { orders: result }));
    } catch (err) {
      util.err("添加订单失败", err);
      res.status(500).json(util.FormatJSONData(500, "服务器内部错误"));
    } finally {
      // 关闭连接（如果已初始化）
      if (goodsDb && typeof goodsDb.disconnect === "function") {
        await goodsDb.disconnect();
      }
      if (db_cart && typeof db_cart.disconnect === "function") {
        await db_cart.disconnect();
      }
    }
  })();
}

//生成订单号
function generateOrderNumber() {
  // 生成日期部分 (14位 yyyyMMddhhmmss)
  const now = new Date();
  const year = now.getFullYear().toString();
  const month = (now.getMonth() + 1).toString().padStart(2, "0");
  const day = now.getDate().toString().padStart(2, "0");
  const hours = now.getHours().toString().padStart(2, "0");
  const minutes = now.getMinutes().toString().padStart(2, "0");
  const seconds = now.getSeconds().toString().padStart(2, "0");

  // 组合日期部分
  const datePart = `${year}${month}${day}${hours}${minutes}${seconds}`;

  // 生成6位随机数（范围 100000 ~ 999999）
  const randomPart = Math.floor(100000 + Math.random() * 900000).toString();

  // 组合最终订单号
  return `${datePart}${randomPart}`;
}

//更改订单状态

function updateorders(req, res) {
  (async () => {
    try {
      const order_id = parseInt(req.query.order_id);
      const order_status = parseInt(req.query.order_status);
      const db = OrdersDB.getInstance();
      await db.connect();
      await db.update(order_id, order_status);
      res.json(
        util.FormatJSONData(200, `设置商品${order_id}状态为${order_status}成功`)
      );
    } catch (err) {
      util.FormatJSONData(res, 500, "服务器内部错误");
    }
  })();
}

//根据orders_id查询
function getByorderid(req, res) {
  (async () => {
    try {
      // 参数校验
      const order_id = req.params.orderid;
      if (isNaN(order_id)) {
        return res.status(400).json(util.FormatJSONData(400, "无效的订单ID"));
      }
      const db = OrdersDB.getInstance();
      await db.connect();
      const order = await db.getByorderid(order_id);
      if (!order) {
        return res.status(404).json(util.FormatJSONData(404, "订单不存在"));
      }
      res.json(util.FormatJSONData(200, "获取订单记录成功", order));
    } catch (err) {
      util.err("查询订单失败");
    }
  })();
}
//根据buyer_id查询
function getBybuyerid(req, res) {
  (async () => {
    try {
      // 参数校验
      const buyer_id = req.params.buyerid;
      if (isNaN(buyer_id)) {
        return res.status(400).json(util.FormatJSONData(400, "无效的买方ID"));
      }
      const db = OrdersDB.getInstance();
      await db.connect();
      const order = await db.getBybuyerid(buyer_id);
      if (!order) {
        return res.status(404).json(util.FormatJSONData(404, "订单不存在"));
      }
      res.json(util.FormatJSONData(200, "获取订单记录成功", order));
    } catch (err) {
      util.err("查询订单失败");
    }
  })();
}
//根据seller_id查询
function getBysellerid(req, res) {
  (async () => {
    try {
      // 参数校验
      const seller_id = req.params.sellerid;
      if (isNaN(seller_id)) {
        return res.status(400).json(util.FormatJSONData(400, "无效的卖方ID"));
      }
      const db = OrdersDB.getInstance();
      await db.connect();
      const order = await db.getBysellerid(seller_id);
      if (!order) {
        return res.status(404).json(util.FormatJSONData(404, "订单不存在"));
      }
      res.json(util.FormatJSONData(200, "获取订单记录成功", order));
    } catch (err) {
      util.err("查询订单失败");
    }
  })();
}

//删除订单
function remove(req, res) {
  (async () => {
    const db = OrdersDB.getInstance();
    await db.connect();
    try {
      const result = await db.remove(req.params.orderid);
      if (!result) {
        res.json(util.FormatJSONData(404, "删除订单记录失败", result));
      } else {
        res.json(util.FormatJSONData(200, "删除订单记录成功", result));
      }
    } catch (err) {
      util.FormatJSONData(res, 500, "服务器内部错误");
    }
  })();
}
module.exports = {
  addorders,
  updateorders,
  getByorderid,
  getBybuyerid,
  getBysellerid,
  remove,
  gopay,
  handleAlipayNotify,
  buyNow
};
